package com.xncoding.freemarker.service;

import com.alibaba.fastjson.JSON;
import com.google.common.base.CaseFormat;
import com.xncoding.freemarker.model.*;
import com.xncoding.freemarker.utile.RegexUtils;
import freemarker.cache.ClassTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;


@Service
public class GenerateCodeService {

    Configuration cfg = null;

    {
        cfg = new Configuration(Configuration.VERSION_2_3_0);
        cfg.setTemplateLoader(new ClassTemplateLoader(GenerateCodeService.class, "/templates"));
        cfg.setDefaultEncoding("UTF-8");
    }

    public RespBean generateCode(List<TableClass> tableClassList, String realPath) {
        try {
            Template modelTemplate = cfg.getTemplate("Model.java.ftl");
            Template serviceTemplate = cfg.getTemplate("Service.java.ftl");
            Template serviceImplTemplate = cfg.getTemplate("serviceImpl.java.ftl");
            Template controllerTemplate = cfg.getTemplate("Controller.java.ftl");
            Template eosTemplate = cfg.getTemplate(".componentType.ftl");
            Template eosFileTemplate = cfg.getTemplate(".eosComponentType.ftl");
            Template eosModelTemplate = cfg.getTemplate(".bizx.ftl");
//            Template eospTemplate = cfg.getTemplate(".eos.ftl");
            for (TableClass tableClass : tableClassList) {

                String path = realPath + "/" + tableClass.getPackageName().replace(".", "/");
                System.out.println(path);
                generate(modelTemplate, tableClass, "Fs"+tableClass.getModelName()+"Input",path + "/dto/"+tableClass.getBusinessName()+"/");
                generate(eosTemplate, tableClass, "Fs"+tableClass.getBusinessName(),path  + "/impl/");
                generate(serviceTemplate, tableClass,"Fs"+tableClass.getBusinessName(), path );
                generate(serviceImplTemplate, tableClass, "Fs"+tableClass.getBusinessName(),path + "/impl/");
                generate(controllerTemplate, tableClass, "Fs"+tableClass.getBusinessName(),realPath + "/com/xjrccb/bizplat/ebank/web");

                generate(eosFileTemplate, tableClass, "Fs"+tableClass.getBusinessName(),path + "/impl/"+tableClass.getBusinessName()+"/");
                generate(eosModelTemplate, tableClass, "get"+tableClass.getModelName(),path + "/impl/"+tableClass.getBusinessName()+"/");
//                generate(eospTemplate, tableClass, path + "/impl/"+tableClass.getBusinessName()+"/");
            }
            return RespBean.ok("代码已生成", realPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("代码生成失败");
    }

    private void generate(Template template, TableClass tableClass,String busName, String path) throws IOException, TemplateException {
        File folder = new File(path);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String fileName = path + "/" + RegexUtils.captureName(busName) + template.getName().replace(".ftl", "").replace("Model", "");
        FileOutputStream fos = new FileOutputStream(fileName);
        OutputStreamWriter out = new OutputStreamWriter(fos);
        template.process(tableClass,out);
        fos.close();
        out.close();
    }

    public RespBean mbankGenerateCode(List<mbank> tableClassList, String realPath) {
        try {
            Template controllerTemplate = cfg.getTemplate("Controller.java.ftl");
            Template serviceTemplate = cfg.getTemplate("Service.java.ftl");
            Template serviceImplTemplate = cfg.getTemplate("ServiceImpl.java.ftl");
            for (mbank tableClass : tableClassList) {
                String path = realPath + "/" + tableClass.getPackageName().replace(".", "/");
                System.out.println(path);
                mbankGenerate(controllerTemplate, tableClass, "Fs"+RegexUtils.captureName(tableClass.getBusinessName()),realPath + "/com/xjrccb/bizplat/mbank/web");
                mbankGenerate(serviceTemplate, tableClass,"Fs"+RegexUtils.captureName(tableClass.getBusinessName()), path );
                mbankGenerate(serviceImplTemplate, tableClass, "Fs"+RegexUtils.captureName(tableClass.getBusinessName()),path + "/impl/");
            }
            return RespBean.ok("代码已生成", realPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("代码生成失败");
    }

    private void mbankGenerate(Template template, mbank tableClass,String busName, String path) throws IOException, TemplateException {
        File folder = new File(path);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String fileName = path + "/" + busName + template.getName().replace(".ftl", "").replace("Model", "");
        System.out.println(JSON.toJSONString(tableClass));
        FileOutputStream fos = new FileOutputStream(fileName);
        OutputStreamWriter out = new OutputStreamWriter(fos);
        template.process(tableClass,out);
        fos.close();
        out.close();
    }

    public RespBean mockGenerateCode(List<mock> tableClassList, String realPath) {
        try {
            Template controllerTemplate = cfg.getTemplate("mockController.java.ftl");

            for (mock mockClass : tableClassList) {
                String path = realPath;
                System.out.println(path);
                mockGenerate01(controllerTemplate, mockClass, "Fs"+RegexUtils.captureName(mockClass.getBusinessName()),realPath);
            }

            Template modelTemplate = cfg.getTemplate("mockModel.java.ftl");
            Template outTemplate = cfg.getTemplate("outModel.java.ftl");
            Template jsonfileTemplate = cfg.getTemplate("jsonModel.json.ftl");
            List<mockCtr> mockCtrList = tableClassList.get(0).getMockcolumns();
            for (mockCtr tableClass : mockCtrList) {
                String path = realPath;
                System.out.println(path);
                mockGenerate(modelTemplate, tableClass, "Fs"+RegexUtils.captureName(tableClass.getModelName())+"Input",path );
                mockGenerate(outTemplate, tableClass, "Fs"+RegexUtils.captureName(tableClass.getModelName())+"Output",path );
                mockGenerate(jsonfileTemplate, tableClass, RegexUtils.uncaptureName(tableClass.getModelName()),path );
            }
            return RespBean.ok("代码已生成", realPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("代码生成失败");
    }

    private void mockGenerate01(Template template, mock tableClass,String busName, String path) throws IOException, TemplateException {
        File folder = new File(path);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String fileName = path + "/" + busName + template.getName().replace(".ftl", "").replace("mock", "");
//        System.out.println(JSON.toJSONString(tableClass));
        FileOutputStream fos = new FileOutputStream(fileName);
        OutputStreamWriter out = new OutputStreamWriter(fos);
        template.process(tableClass,out);
        fos.close();
        out.close();
    }

    private void mockGenerate(Template template, mockCtr tableClass,String busName, String path) throws IOException, TemplateException {
        File folder = new File(path);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        String fileName = path + "/" + busName + template.getName().replace(".ftl", "").replace("mockModel", "").replace("outModel","").replace("jsonModel","");
//        System.out.println(JSON.toJSONString(tableClass));
        FileOutputStream fos = new FileOutputStream(fileName);
        OutputStreamWriter out = new OutputStreamWriter(fos);
        template.process(tableClass,out);
        fos.close();
        out.close();
    }


}


